package groep3.ssc.tmts;

import groep3.ssc.helpers.Encryption;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class TMTSFinder implements Runnable
{
    private static final int BROADCAST_PORT = 1400;
    private static final TMTSFinder INSTANCE = new TMTSFinder();
    private static final String EXPECTED_MESSAGE = "TMTS_SERVER";
    private static final String RESPONSE_MESSAGE = "TMTS_CLIENT";
    private DatagramSocket socket;
    private DatagramPacket packet;
    private byte[] recvBuf;
    private DatagramPacket sendPacket;
    private byte[] sendData;
    public static boolean searching = true;

    public static TMTSFinder getInstance()
    {
        return TMTSFinder.INSTANCE;
    }

    private TMTSFinder()
    {
        try
        {
            socket = new DatagramSocket(BROADCAST_PORT, InetAddress.getByName("0.0.0.0"));
            socket.setBroadcast(true);
        } catch (SocketException e)
        {
            e.printStackTrace();
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        try
        {
            while (true)
            {
                if (!searching)
                {
                    break;
                }

                //Receive a packet
                recvBuf = new byte[15000];
                packet = new DatagramPacket(recvBuf, recvBuf.length);
                socket.receive(packet);

                //See if the packet holds the right command (message)
                String message = null;

                try
                {
                    message = Encryption.decrypt(new String(packet.getData()).trim());
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
                if (message != null && message.equals(EXPECTED_MESSAGE))
                {
                    sendData = (RESPONSE_MESSAGE + " " + BROADCAST_PORT).getBytes();

                    //Send a response
                    sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
                    socket.send(sendPacket);
                }
            }
        } catch (IOException ex)
        {
            Logger.getLogger(TMTSFinder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
